package com.ningjingjing.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ningjingjing.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * 1.判断用户是否登录
 * 2.根据API结果格式规定，构建相应的对象
 * 3.把对象序列化成JSON字符串
 * 4.将结果写入resp对象中
 */



@WebServlet("/api/current-user.json")
public class currentUserApi extends HttpServlet {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //这里的代码用于临时测试，一会儿删掉
//        {
//            User user = new User();
//            user.uid = 001;
//            user.username ="ningjingjing";
//            user.nickname = "宁静静";
//            HttpSession session = req.getSession();
//            session.setAttribute("currentUser", user);
//
//        }


        //判定目前是否有用户处于登陆状态
        HttpSession session = req.getSession();
        User currentUser = (User)session.getAttribute("currentUser");
        Object result;
        if (currentUser == null){
            //用户未登录
            result = new Object(){
                public boolean logged = false;
            };
        }else {
            //用户已登录
            result = new Object(){
                public boolean logged = true;
                public User user = currentUser;
            };
        }

        //将对象序列化成JSON字符串
        String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(json);
    }
}
